import io

from django.http import JsonResponse, HttpRequest
from django.shortcuts import render, redirect

from polls.models import Subject, Teacher, User
from polls.utils import Captcha, gen_random_code, gen_md5_digest
from io import BytesIO
from pipes import quote

import xlwt as xlwt
from django.http import HttpResponse

from polls.models import Subject

def show_subjects(request):
    subjects = Subject.objects.all().order_by('no')
    return render(request, 'subjects.html', {'subjects': subjects})


def show_teachers(request):
    try:
        sno = int(request.GET.get('sno'))
        teachers = []
        if sno:
            subject = Subject.objects.only('name').get(no=sno)
            teachers = Teacher.objects.filter(subject=subject).order_by('no')
        return render(request, 'teachers.html', {
            'subject': subject,
            'teachers': teachers
        })
    except (ValueError, Subject.DoesNotExist):
        return redirect('/')

def praise_or_criticize(request:HttpRequest) -> HttpRequest:
    if request.session.get('userid'):
        try:
            tno = int(request.GET.get('tno'))
            teacher = Teacher.objects.get(no = tno)
            if request.path.startswith('/praise/'):
                teacher.good_count += 1
                count = teacher.good_count
            else:
                teacher.bad_count +=1
                count = teacher.bad_count
            teacher.save()
            data = {'code':20000,'mesg':'投票成功','count':count}
        except(ValueError,Teacher.DoesNotExist):
            data = {'code':20001,'mesg':'投票失败'}
    else:
        data = {'code':20002,'mesg':'请先登录'}




def get_captcha(request:HttpRequest) -> HttpRequest:
    '''验证码'''
    captcha_text = gen_random_code()
    request.session['captcha'] = captcha_text
    image_data = Captcha.instance().generate(captcha_text)
    return HttpRequest(image_data,content_type='image/png')

def login(request:HttpRequest) -> HttpRequest:
    '''登录'''
    hint = ''
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username and password:
            password = gen_md5_digest(password)
            user = User.objects.filter(username=username,password=password).first()
            if user:
                request.session['userId'] = user.no
                request.session['username'] = user.username
            else:
                hint = '用户名或者密码错误'
        else:
            hint='请输入有效的用户名和密码'
    return render(request,'login.html',{'hint':hint})

def logout(request):
    '''注销'''
    request.session.flush()
    return redirect('/')


def export_excel():
    wb = xlwt.Wordbook()
    sheet = wb.add_sheet('科目信息表')
    queryset = Teacher.objects.all()
    colnames = ('学号','名称','性别','生日','介绍','好评数','坏评数','坏评数','号码')
    for index,no in enumerate(colnames):
        sheet.write(0,index,no)
    props = ('no','name','intro','is_hot')
    for row,teacher in enumerate(queryset):
        for col,prop in enumerate(props):
            value = getattr(teacher,prop,'')
            if isinstance(value,Subject):
                value = value.name
            sheet.write(row+1,col,value)
    '''保存excel'''
    buffer = BytesIO()
    wb.save(buffer)
    resp = HttpResponse(buffer.getvalue(),content_type='application/vnd.ms-excel')
    filename = quote('科目.xls')
    resp['content-disposition'] = f'attachment; filename*=utf-8\'\'{filename}'
    return resp

def export_pdf(request: HttpRequest) -> HttpResponse:
    buffer = io.BytesIO()
    import canvas
    pdf = canvas.Canvas(buffer)
    pdf.setFont("Helvetica", 80)
    pdf.setFillColorRGB(0.2, 0.5, 0.3)
    pdf.drawString(100, 550, 'hello, world!')
    pdf.showPage()
    pdf.save()
    resp = HttpResponse(buffer.getvalue(), content_type='application/pdf')
    resp['content-disposition'] = 'inline; filename="demo.pdf"'
    return resp

def get_teachers_data(request):
    queryset = Teacher.objects.all()
    names = [teacher.name for teacher in queryset]
    good_counts = [teacher.gcount for teacher in queryset]
    bad_counts = [teacher.bcount for teacher in queryset]
    return JsonResponse({'names': names, 'good': good_counts, 'bad': bad_counts})